package com.appsky.drift.activity;

import com.alibaba.fastjson.JSONObject;
import com.appsky.drift.R;
import com.appsky.drift.api.AppSkyApp;
import com.appsky.drift.api.JsonFactory;
import com.appsky.drift.api.Utils;
import com.appsky.drift.dialog.AboutDialog;
import com.appsky.drift.dialog.EnterNickAndSexDialog;
import com.appsky.drift.dialog.RoomPersonListDialog;

import android.app.ActivityGroup;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

public class ChatMainActivity extends ActivityGroup implements OnClickListener {

	private static final int QUIT_DIALOG = 0;

	private LinearLayout container = null;

	private TextView tabTraditionMod, tabMapMod;

	private EditText editText;

	private Button sendButton;

	private JsonFactory jsonFactory = JsonFactory.getFactory();

	private AppSkyApp app;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.chat_main_layout);

		initView();

		app = (AppSkyApp) getApplication();

		onClick(tabTraditionMod);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		MenuItem changeInfo = menu.add(0, 0, 0, R.string.set_user_info);
		changeInfo.setIcon(R.drawable.ic_edit);

		MenuItem roomPerson = menu.add(0, 1, 0, R.string.room_person_list);
		roomPerson.setIcon(R.drawable.ic_room_person);

		MenuItem quitRoom = menu.add(0, 2, 0, R.string.quit_room);
		quitRoom.setIcon(R.drawable.quit_room);

		MenuItem about = menu.add(0, 3, 0, R.string.about);
		about.setIcon(R.drawable.ic_about);
		
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			showDialog(QUIT_DIALOG);
		}
		return super.onKeyUp(keyCode, event);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case QUIT_DIALOG:
			if (app.myInfo.isRoomOwner()
					&& app.myInfo.getRoomPersons().size() > 0) {
				return new AlertDialog.Builder(ChatMainActivity.this)
						.setIcon(R.drawable.ic_dialog_alert)
						.setTitle(R.string.can_not_quit_room)
						.setPositiveButton(R.string.ok,
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
									}
								}).show();
			} else {
				return new AlertDialog.Builder(ChatMainActivity.this)
						.setIcon(R.drawable.ic_interrogative)
						.setTitle(R.string.sure_quit_room)
						.setPositiveButton(R.string.ok,
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										finish();
									}
								})
						.setNegativeButton(R.string.cancel,
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
									}
								}).show();
			}
		default:
			return super.onCreateDialog(QUIT_DIALOG);
		}
	}

	@Override
	protected void onDestroy() {
		JSONObject json = jsonFactory.makeQuitRoomJson(app.myInfo.getUserId(),
				app.myInfo.getRoomId());
		Intent intent = new Intent(Utils.ACTION_SEND_MESSAGE);
		intent.putExtra("json", json.toJSONString());
		sendBroadcast(intent);
		app.myInfo.setRoomId(-1);
		super.onDestroy();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case 0:
			new EnterNickAndSexDialog(this).show();
			break;
		case 1:
			final ProgressDialog progressDialog = new ProgressDialog(this);
			progressDialog.setMessage("正在获取用户列表");
			progressDialog.show();
			JSONObject json = jsonFactory.makeQueryRoomPersonJson(app.myInfo
					.getUserId());
			Intent intent = new Intent(Utils.ACTION_SEND_MESSAGE);
			intent.putExtra("json", json.toJSONString());
			sendBroadcast(intent);
			app.obtainMessageHandler = new Handler() {

				@Override
				public void handleMessage(Message msg) {
					if (progressDialog != null) {
						progressDialog.dismiss();
					}
					new RoomPersonListDialog(ChatMainActivity.this).show();
					super.handleMessage(msg);
				}

			};
			break;
		case 2:
			showDialog(QUIT_DIALOG);
			break;
		case 3:
			new AboutDialog(ChatMainActivity.this).show();
			break;
		}

		return true;
	}

	private Intent tabIntent = null;

	@Override
	public void onClick(View v) {
		setIntentAndButtonState(v.getId());
		startTabActivity(v.getId());
	}

	private void initView() {
		container = (LinearLayout) findViewById(R.id.activity_container);
		tabTraditionMod = (TextView) findViewById(R.id.tab_tradition_mod);
		tabTraditionMod.setOnClickListener(this);
		tabMapMod = (TextView) findViewById(R.id.tab_map_mod);
		tabMapMod.setOnClickListener(this);

		editText = (EditText) findViewById(R.id.edit_text);
		sendButton = (Button) findViewById(R.id.send_button);
		sendButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String string = editText.getText().toString();
				if (Utils.isNotNullString(string.trim())) {
					JSONObject json = jsonFactory.makeSayContentJson(
							app.myInfo.getUserId(), string,
							app.myInfo.getNick(), app.myInfo.getSex());
					editText.setText(null);
					Intent intent = new Intent(Utils.ACTION_SEND_MESSAGE);
					intent.putExtra("json", json.toJSONString());
					sendBroadcast(intent);
					Intent intentForMe = new Intent(
							Utils.ACTION_CHAT_MESSAGE_RECEIVER);
					// 这里是给自己发的广播，所以只要data字段
					json = json.getJSONObject("data");
					intentForMe.putExtra("json", json.toJSONString());
					sendBroadcast(intentForMe);
				} else {
					Toast.makeText(ChatMainActivity.this,
							R.string.content_not_null, Toast.LENGTH_SHORT)
							.show();
				}
			}
		});
	}

	private void startTabActivity(int id) {
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		View activityView = getLocalActivityManager().startActivity(
				String.valueOf(id), tabIntent).getDecorView();
		container.addView(activityView, lp);
	}

	private void setIntentAndButtonState(int id) {

		container.removeAllViews();
		setAllButtonDefault();

		switch (id) {
		case R.id.tab_tradition_mod:
			tabIntent = new Intent(this, ChatTraditionActivity.class);
			setTabButtonState(tabTraditionMod,
					R.drawable.ic_tab_tradition_selected, Color.WHITE);
			break;
		case R.id.tab_map_mod:
			tabIntent = new Intent(this, ChatMapModActivity.class);
			setTabButtonState(tabMapMod, R.drawable.ic_tab_map_selected,
					Color.WHITE);
			break;
		default:
			tabIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			break;
		}
	}

	private void setAllButtonDefault() {
		setTabButtonState(tabTraditionMod, R.drawable.ic_tab_tradition_default,
				Color.GRAY);
		setTabButtonState(tabMapMod, R.drawable.ic_tab_map_default, Color.GRAY);
	}

	private void setTabButtonState(TextView tabButton, int drawId, int textColor) {
		tabButton.setCompoundDrawablesWithIntrinsicBounds(0, drawId, 0, 0);
		tabButton.setTextColor(textColor);
	}

}
